package pers.mihao.quickstream.common.task.domain.scheduler;

import java.util.Date;
import org.quartz.CronExpression; // 需要添加 Quartz 依赖
import pers.mihao.quickstream.common.exception.BizException;
import pers.mihao.quickstream.common.task.scheduler.TaskInvokeRes;

import java.text.ParseException;

/**
 * @author mihao
 * @since 2024/11/15
 */
public class CronAutomaticTaskTimer implements AutomaticTaskTimer {
    private String cronExpress;

    public CronAutomaticTaskTimer(String cronExpress) {
        check(cronExpress);
        this.cronExpress = cronExpress;
    }

    private void check(String cronExpress) {
        // 验证 cron 表达式是否合法
        try {
            new CronExpression(cronExpress);
        } catch (ParseException e) {
            throw new IllegalArgumentException("Invalid cron expression: " + cronExpress);
        }
    }

    @Override
    public Date getNextInvokeTime(TaskInvokeRes lastTaskInvokeRes, int invokeNum) {
        try {
            CronExpression cronExpression = new CronExpression(cronExpress);
            Date now = new Date(); // 当前时间
            return cronExpression.getNextValidTimeAfter(now); // 获取下一个有效时间
        } catch (ParseException e) {
            throw new BizException("Error while parsing cron expression", e);
        }
    }

    @Override
    public String type() {
        return "CRON";
    }
}

